'use strict';
let doubanbook = require("doubanbook");
exports.main = async (event, context) => {
    let { isbn } = event;
	const db = uniCloud.database()
	
	// 查询当前数据库里面是否存在待查询的数据
	let dbResult = await db.collection("books").limit(1).where({
		isbn:isbn
	}).get()
	console.log("dbResult", dbResult)
	
	if(dbResult.affectedDocs > 0){
		// 查询本地库
		return dbResult.data
	}else{
		// 查询远程数据
		// let res = await uniCloud.httpclient.request("https://search.douban.com/book/subject_search?search_text=" + isbn + "&cat=1001");
		let res = await uniCloud.httpclient.request(`https://api.zuk.pw/situ/book/isbn/`+isbn);
		let resObj = JSON.parse(res.data.toString()) 
		
		// 处理图片
		let photoUrlbuffer = await uniCloud.httpclient.request(resObj.data.photoUrl)
		let uploadPhotoResult = await uniCloud.uploadFile({
			cloudPath: isbn+".png",
			fileContent: photoUrlbuffer.data
		})
		
		// 存库
		await db.collection("books").add({...resObj.data,...{
			photoUrl: uploadPhotoResult.fileID,
			isbn: isbn
		}})
		
		// 返回数据给客户端
		return resObj
	}
	
};
